<template>
  <div class="room-list-container">
    <el-card class="filter-card">
      <div class="filter-header">
        <h2>房间列表</h2>
        <div class="filter-actions">
          <el-input v-model="searchHotelName" placeholder="输入酒店名称搜索" clearable @clear="handleClear" style="width: 250px;">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="filterByHotel">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>
      
      <!-- 优化筛选选项布局 -->
      <div class="filter-section">
        <div class="filter-section-content">
          <div class="filter-group">
            <div class="filter-item">
              <span class="filter-label">早餐：</span>
              <el-select v-model="breakfastFilter" placeholder="早餐选项" clearable @change="applyFilters" style="width: 150px;">
                <el-option label="含早餐" value="1" />
                <el-option label="不含早餐" value="0" />
              </el-select>
            </div>
            
            <div class="filter-item">
              <span class="filter-label">价格区间：</span>
              <div class="slider-container">
                <el-slider
                  v-model="priceRange"
                  range
                  :min="minPrice"
                  :max="maxPrice"
                  :step="50"
                  @change="applyFilters"
                  style="width: 250px;"
                />
                <span class="price-display">{{ priceRange[0] }} - {{ priceRange[1] }} 元</span>
              </div>
            </div>
            
            <div class="filter-item filter-reset">
              <el-button type="primary" @click="resetAllFilters">重置筛选</el-button>
            </div>
          </div>
        </div>
        
        <div v-if="activeFilter || activeFilterTags.length > 0" class="active-filter-section">
          <div class="filter-tag-container">
            <el-tag closable @close="handleClear" v-if="activeFilter">
              {{ activeFilter }}
            </el-tag>
            <el-tag 
              v-for="(tag, index) in activeFilterTags" 
              :key="index" 
              closable 
              @close="removeFilter(tag.type)"
              type="success"
              class="filter-tag"
            >
              {{ tag.label }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-card>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else>
      <div v-if="filteredRoomList.length === 0" class="empty-container">
        <el-empty description="暂无可用房间" />
      </div>
      
      <el-row :gutter="20" v-else>
        <el-col :span="24" v-for="room in filteredRoomList" :key="`${room.hotelName}-${room.roomType}`" class="room-card-col">
          <el-card class="room-card" shadow="hover">
            <div class="room-layout">
              <div class="room-image">
                <img :src="room.image || '/src/assets/default.png'" alt="房间图片">
              </div>
              <div class="room-info">
                <h3 class="room-type">{{ room.roomType }}</h3>
                <div class="hotel-name">
                  <el-icon><House /></el-icon>
                  <span>{{ room.hotelName }}</span>
                </div>
                <div class="room-meta">
                  <div class="room-price">¥ {{ room.price }} <span>/ 晚</span></div>
                  <div class="room-available">剩余: {{ room.availableCount }} 间</div>
                </div>
                <div class="room-features">
                  <el-tag size="small" v-if="room.breakfast === '1'" type="success">含早餐</el-tag>
                  <el-tag size="small" v-else>不含早餐</el-tag>
                </div>
                <div class="room-actions">
                  <el-button type="primary" @click="createOrder(room)" :disabled="room.availableCount <= 0">
                    预订房间
                  </el-button>
                  <el-button type="info" @click="viewHotelRooms(room.hotelName)">
                    查看酒店详情
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <div class="pagination-box">
        <el-pagination 
          background 
          layout="total, sizes, prev, pager, next"
          v-model:current-page="pageIndex"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :total="total"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getRoomList, getRoomsByHotel } from '@/api/room'
import { ElMessage } from 'element-plus'
import { Search, House } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const roomList = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(12)
const loading = ref(true)
const searchHotelName = ref('')
const activeFilter = ref('')

// 筛选相关
const minPrice = ref(0)
const maxPrice = ref(5000) // 默认最大价格
const priceRange = ref([0, 5000])
const breakfastFilter = ref('')
const activeFilterTags = ref([])

// 筛选后的房间列表
const filteredRoomList = computed(() => {
  // 如果没有筛选条件，直接返回原始数据
  if (priceRange.value[0] === minPrice.value && 
      priceRange.value[1] === maxPrice.value && 
      !breakfastFilter.value) {
    return roomList.value
  }
  
  return roomList.value.filter(room => {
    // 价格筛选
    const price = parseFloat(String(room.price))
    const passPriceFilter = price >= priceRange.value[0] && price <= priceRange.value[1]
    
    // 早餐筛选
    const passBreakfastFilter = !breakfastFilter.value || room.breakfast === breakfastFilter.value
    
    // 同时满足两个条件
    return passPriceFilter && passBreakfastFilter
  })
})

// 应用筛选条件
const applyFilters = () => {
  // 更新活动筛选标签
  activeFilterTags.value = []
  
  // 价格筛选标签
  if (priceRange.value[0] > minPrice.value || priceRange.value[1] < maxPrice.value) {
    activeFilterTags.value.push({
      type: 'price',
      label: `价格: ${priceRange.value[0]}-${priceRange.value[1]}元`
    })
  }
  
  // 早餐筛选标签
  if (breakfastFilter.value) {
    activeFilterTags.value.push({
      type: 'breakfast',
      label: breakfastFilter.value === '1' ? '含早餐' : '不含早餐'
    })
  }
  
  // 更新URL参数
  router.push({
    query: {
      ...route.query,
      minPrice: priceRange.value[0],
      maxPrice: priceRange.value[1],
      ...(breakfastFilter.value ? { breakfast: breakfastFilter.value } : {})
    }
  })
}

// 移除特定筛选条件
const removeFilter = (filterType) => {
  if (filterType === 'price') {
    priceRange.value = [minPrice.value, maxPrice.value]
  } else if (filterType === 'breakfast') {
    breakfastFilter.value = ''
  }
  
  // 重新应用筛选
  applyFilters()
}

// 重置所有筛选条件
const resetAllFilters = () => {
  priceRange.value = [minPrice.value, maxPrice.value]
  breakfastFilter.value = ''
  activeFilterTags.value = []
  
  // 清除URL中的筛选参数
  const query = { ...route.query }
  delete query.minPrice
  delete query.maxPrice
  delete query.breakfast
  router.push({ query })
}

// 获取房间价格区间
const calculatePriceRange = () => {
  if (roomList.value.length === 0) {
    return
  }
  
  // 找出最低和最高价格
  let min = Number.MAX_SAFE_INTEGER
  let max = 0
  
  roomList.value.forEach(room => {
    const price = parseFloat(String(room.price))
    if (price < min) min = price
    if (price > max) max = price
  })
  
  // 设置价格区间（稍微扩大一点范围）
  minPrice.value = Math.max(0, Math.floor(min / 100) * 100)
  maxPrice.value = Math.ceil(max / 100) * 100 + 500
  
  // 初始化价格筛选范围
  priceRange.value = [minPrice.value, maxPrice.value]
}

// 从URL恢复筛选条件
const restoreFiltersFromUrl = () => {
  const { minPrice: urlMinPrice, maxPrice: urlMaxPrice, breakfast } = route.query
  
  if (urlMinPrice && urlMaxPrice) {
    priceRange.value = [parseInt(urlMinPrice as string, 10), parseInt(urlMaxPrice as string, 10)]
  }
  
  if (breakfast) {
    breakfastFilter.value = breakfast as string
  }
  
  // 如果有筛选条件，应用它们
  if (urlMinPrice || urlMaxPrice || breakfast) {
    applyFilters()
  }
}

// 获取所有房间列表
const fetchAllRooms = async () => {
  loading.value = true
  
  try {
    const res = await getRoomList({ pageIndex: pageIndex.value, pageSize: pageSize.value })
    const result = res.data
    
    if (result && result.code === 200) {
      roomList.value = Array.isArray(result.data) ? result.data : []
      total.value = roomList.value.length
      console.log('获取到的房间列表:', roomList.value)
      
      // 计算价格区间
      calculatePriceRange()
      
      // 恢复URL中的筛选条件
      restoreFiltersFromUrl()
    } else {
      ElMessage.error(result?.msg || '获取房间列表失败')
    }
  } catch (error) {
    console.error('获取房间列表错误:', error)
    ElMessage.error('网络错误，获取房间列表失败')
  } finally {
    loading.value = false
  }
}

// 按酒店名称获取房间
const fetchRoomsByHotel = async () => {
  if (!searchHotelName.value) return
  
  loading.value = true
  
  try {
    const res = await getRoomsByHotel(searchHotelName.value)
    const result = res.data
    
    if (result && result.code === 200) {
      roomList.value = Array.isArray(result.data) ? result.data : []
      total.value = roomList.value.length
      console.log('按酒店筛选的房间列表:', roomList.value)
      
      // 计算价格区间
      calculatePriceRange()
      
      // 恢复URL中的筛选条件
      restoreFiltersFromUrl()
    } else {
      ElMessage.error(result?.msg || '获取酒店房间失败')
    }
  } catch (error) {
    console.error('获取酒店房间错误:', error)
    ElMessage.error('网络错误，获取酒店房间失败')
  } finally {
    loading.value = false
  }
}

// 初始化数据
const initData = async () => {
  // 如果已经在通过watch处理URL参数，则不重复处理
  if (route.query.hotelName) {
    return
  }
  
  await fetchAllRooms()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  initData()
}

const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  initData()
}

// 创建订单
const createOrder = (room) => {
  router.push({
    path: '/create-order',
    query: {
      hotelName: room.hotelName,
      roomType: room.roomType
    }
  })
}

// 查看酒店详情
const viewHotelRooms = (hotelName) => {
  // 跳转到酒店列表并进行搜索
  router.push({
    path: '/hotel',
    query: { searchName: hotelName }
  })
}

// 重置筛选
const resetFilter = (reload = true) => {
  searchHotelName.value = ''
  activeFilter.value = ''
  
  // 清除URL参数中的hotelName
  const query = { ...route.query }
  delete query.hotelName
  router.push({ query })
  
  if (reload) {
    fetchAllRooms()
  }
}

// 处理清除事件
const handleClear = () => {
  resetFilter(true)
}

// 按酒店名称筛选
const filterByHotel = () => {
  if (!searchHotelName.value) {
    resetFilter()
    return
  }
  
  activeFilter.value = `酒店: ${searchHotelName.value}`
  fetchRoomsByHotel()
  
  // 更新URL参数，不刷新页面
  router.push({
    query: { ...route.query, hotelName: searchHotelName.value }
  })
}

// 最后添加watch和onMounted，确保所有引用的函数都已定义
// 监听路由参数变化
watch(() => route.query.hotelName, (newVal) => {
  if (newVal) {
    searchHotelName.value = newVal as string
    activeFilter.value = `酒店: ${newVal}`
    fetchRoomsByHotel()
  } else if (route.path === '/rooms') {
    // 当没有酒店名称参数时，获取所有房间
    fetchAllRooms()
  }
}, { immediate: true })

onMounted(() => {
  // 确保页面加载时有数据
  if (!route.query.hotelName && route.path === '/rooms') {
    fetchAllRooms()
  }
})
</script>

<style scoped>
.room-list-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
}

/* 优化筛选部分样式 */
.filter-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-top: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.filter-section-content {
  padding: 20px;
}

.filter-group {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 30px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.slider-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 10px;
  width: 250px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  margin-right: 10px;
}

.price-display {
  font-size: 14px;
  color: #606266;
  text-align: center;
}

.filter-reset {
  margin-left: auto;
}

.active-filter-section {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}

.filter-tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-tag {
  margin-right: 5px;
}

/* 保留其他已有样式 */
.loading-container, .empty-container {
  padding: 40px;
  text-align: center;
}

.room-card-col {
  margin-bottom: 20px;
}

.room-card {
  width: 100%;
  transition: transform 0.3s;
}

.room-card:hover {
  transform: translateY(-5px);
}

.room-layout {
  display: flex;
  gap: 20px;
}

.room-image {
  width: 200px;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
}

.room-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.room-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.room-type {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
}

.hotel-name {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  margin-bottom: 10px;
  font-size: 14px;
}

.room-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.room-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.room-price span {
  font-size: 14px;
  font-weight: normal;
  color: #909399;
}

.room-available {
  font-size: 14px;
  color: #409EFF;
}

.room-features {
  margin-bottom: 15px;
}

.room-actions {
  margin-top: auto;
  display: flex;
  gap: 10px;
}

.pagination-box {
  padding-top: 20px;
  display: flex;
  justify-content: right;
}

@media (max-width: 768px) {
  .room-layout {
    flex-direction: column;
  }
  
  .room-image {
    width: 100%;
    height: 200px;
  }
  
  .filter-group {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    width: 100%;
    margin-bottom: 15px;
  }
  
  .slider-container {
    width: 100%;
  }
  
  .filter-reset {
    margin-left: 0;
  }
}
</style> 